package com.hyfrogx.modules.charge.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyfrogx.common.param.Constants;
import com.hyfrogx.common.param.JSONResult;
import com.hyfrogx.common.param.PayType;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.common.utils.R;
import com.hyfrogx.common.utils.Terminal;
import com.hyfrogx.common.validator.ValidatorUtils;
import com.hyfrogx.modules.app.entity.User;
import com.hyfrogx.modules.app.service.UserService;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.charge.entity.HyCharge;
import com.hyfrogx.modules.charge.form.BackDoorForm;
import com.hyfrogx.modules.charge.form.ChargeForm;
import com.hyfrogx.modules.charge.service.HyChargeService;
import com.hyfrogx.modules.manage.entity.HyProductionScaleEntity;
import com.hyfrogx.modules.manage.entity.chargePayRecord.ChargePayRecordEntity;
import com.hyfrogx.modules.manage.entity.payrecord.HyPayRecord;
import com.hyfrogx.modules.manage.service.HyPayRecordService;
import com.hyfrogx.modules.manage.service.HyProductionVacuateService;
import com.hyfrogx.modules.manage.service.chargePayRecord.ChargePayRecordService;
import com.hyfrogx.modules.sys.controller.AbstractController;
import com.hyfrogx.modules.zoom.entity.HyNmtPower;
import com.hyfrogx.modules.zoom.form.NmtPowerForm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * @author ：Li9527
 * @date ：Created in 2019-11-22 14:35
 * @description：${description}
 * @modified By：
 * @version: 1.0.0
 */
@RestController
@RequestMapping("/charge")
@Api(value = "充值内容管理controller", tags = {"后台--充值内容管理"})
public class HyChargeController extends AbstractController {

    @Autowired
    HyChargeService chargeService;

    @Autowired
    HyProductionVacuateService vacuateService;
    @Autowired
    ChargePayRecordService chargePayRecordService;
    @Autowired
    UserService userService;
    @Autowired
    HyPayRecordService payRecordService;

    /**
     * 分页查询充值模板
     *
     * @param params
     * @return
     */
    @GetMapping("getList")
    @ApiOperation("分页查询充值模板")
    public R getList(@RequestParam Map<String, Object> params) {
        Page page = chargeService.selectPageByConditions(new QueryExt(params));
        if (page.getRecords() != null) {
            return R.ok().put("page", page);
        } else {
            return R.error("获取失败");
        }
    }


    /**
     * 创建充值模板
     *
     * @param
     * @return
     */
    @PostMapping("create")
    @ApiOperation("创建充值模板")
    public R createCharge(@RequestBody ChargeForm form) {
        ValidatorUtils.validateClientEntity(form);
        HyCharge charge = new HyCharge();
        BeanUtils.copyProperties(form,charge);
        charge.setCreateDate(new Date());
        charge.setUpdateDate(new Date());
        // 默认禁用
        charge.setStatus(FrogConstant.BasicStatus.FLASE.getValue());
        charge.setCuid(getUserId().intValue());
        Boolean flag = chargeService.save(charge);
        if(flag){
            return R.ok("新增成功");
        }else{
            return R.error("新增失败");
        }
    }

    /**
     * 编辑充值模板
     *
     * @param form
     * @return
     */
    @PostMapping("/edit")
    @ApiOperation("编辑充值模板")
    public R editCharge(@RequestBody ChargeForm form) {
        if (form.getId() == null) {
            return R.error("编辑充值模板时主键id必传");
        }
        ValidatorUtils.validateClientEntity(form);
        HyCharge charge = new HyCharge();
        BeanUtils.copyProperties(form, charge);
        charge.setUpdateDate(new Date());
        charge.setLastEuid(getUserId().intValue());
        Boolean flag = chargeService.updateById(charge);
        if(flag){
            return R.ok("编辑成功");
        }else{
            return R.error("编辑失败");
        }
    }

    /**
     * 获取安卓充值比例
     * @param
     * @return
     */
    @GetMapping("/android/scale/get")
    @ApiOperation("获取安卓充值比例")
    public R getScale() {
        // 获取安卓充值比例
        HyProductionScaleEntity vipScale = vacuateService.getOne(new QueryWrapper<HyProductionScaleEntity>().eq("param_key",FrogConstant.SysConfigKey.ANDROID_CHARGE_SCALE));
        if(ObjectUtil.isNull(vipScale)){
            return R.error("安卓充值比例配置丢失");
        }else{
            return R.ok().put("data",vipScale);
        }
    }

    @ApiOperation("删除模板")
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public R delete(@RequestBody HyCharge charge) {
        try {
            if(charge.getId() == null){
                return R.error("id不能为空");
            }
            chargeService.delete(charge);
            return R.ok();
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }


    @ApiOperation("管理后台充值记录列表")
    @GetMapping("record/get")
    public R getChargePayRecord(@RequestParam Map<String, Object> params) {
        Page page = chargePayRecordService.findByPage(new QueryExt(params));
        if (page.getRecords() != null) {
            return R.ok().put("page", page);
        } else {
            return R.error("获取失败");
        }
    }


    /**
     * 后台充值蛙豆
     * @param form
     * @return
     */
    @ApiOperation("后台充值蛙豆")
    @RequestMapping(value = "coin", method = RequestMethod.POST)
    public R coin(@RequestBody BackDoorForm form) {
        try {
            Long ll =this.getUserId();
           // User user = (User)SecurityUtils.getSubject().getPrincipal();
            if(!ll .equals(FrogConstant.admin_uid)){
                return R.error("您不是超级管理员账号，没有后门充值权限。");
            }
            String phone = form.getPhone();
            User u = userService.getUserByPhone(form.getPhone());
            Integer num = form.getNum();
            if(num == null){
                return R.error("充值蛙豆数量必传");
            }
            if (u == null){
                return R.error("手机号不存在");
            }else{
                Long uid =Long.parseLong(u.getUid().toString()) ;
                //userVipService.addCoinBackDoor(uid, num);
                userService.addBean(u.getUid().longValue(),num);
                logger.info("coin:"+ll+"*****"+phone+"*****"+num);
                // 生成订单
                HyPayRecord payRecord = new HyPayRecord();
                payRecord.setCreatedate(new Date());
                //payRecord.setGid(0);
                payRecord.setTotal(num);
                payRecord.setMoney(num);
                payRecord.setNum(0);
                payRecord.setType(PayType.backdoor_coin.getCode());
               // payRecord.setCid(0);
               // payRecord.setChannel(0);
                payRecord.setPercentCoin(0);
                payRecord.setPercent(0.0f);
                payRecord.setYid(Long.parseLong(u.getUid().toString()));
                // 扣费者id
                payRecord.setUid(FrogConstant.admin_uid);
                //payRecord.setVid(0);
                payRecordService.save(payRecord);

                // 生成交易明细
                ChargePayRecordEntity chargePayRecord = new ChargePayRecordEntity();
                chargePayRecord.setUid(uid);
                Calendar now = Calendar.getInstance();
                int year = now.get(Calendar.YEAR);
                int month = now.get(Calendar.MONTH) + 1;
                String monthN;
                if(month < 10){
                    monthN = "0" + month + "";
                }else{
                    monthN = month + "";
                }
                int day = now.get(Calendar.DAY_OF_MONTH);
                chargePayRecord.setOutTradeNo(year + "" + monthN  + day  + "" +  System.currentTimeMillis() + "");
                chargePayRecord.setTotalAmount(0);
                chargePayRecord.setCoin(num);
                chargePayRecord.setType(0);
                //chargePayRecord.setPresentCoin(0);
                chargePayRecord.setCreateDate(new Date());
                chargePayRecord.setReceiptAmount(new BigDecimal(0));
                chargePayRecord.setBuyerPayAmount(new BigDecimal(0));
                chargePayRecord.setUpdateDate(new Date());
                chargePayRecord.setChargePresentCoin(0);
                chargePayRecord.setStatus(Constants.PayStatus.SUCCESS);
                chargePayRecord.setTerminal(Terminal.DisplayChannel.system);
                chargePayRecord.setChannel(Constants.PayChannel.SYSTEM_COIN);
                if(form.getRemark() != null){
                    chargePayRecord.setRemark(form.getRemark());
                }
                chargePayRecordService.save(chargePayRecord);
                return R.ok("充值成功");
            }
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 后台扣减蛙豆
     * @param form
     * @return
     */
    @ApiOperation("后台扣减蛙豆")
    @PostMapping(value = "reduce")
    public R reduce(@RequestBody BackDoorForm form ) {
        try {
            String phone = form.getPhone();
            String remark = form.getRemark();
            Integer num = form.getNum();
            User u = userService.getUserByPhone(form.getPhone());
            Long ll =this.getUserId();
           // User user = (User)SecurityUtils.getSubject().getPrincipal();
            if(!ll.equals(FrogConstant.admin_uid)){
                return R.error("您不是超级管理员账号，没有后门充值权限。");
            }
            if(num == null){
                return R.error("充值蛙豆数量必传");
            }
            if (u == null){
                return R.error("手机号不存在");
            }else{
                Long uid =Long.parseLong(u.getUid().toString()) ;
                userService.reduce(u.getUid().longValue(),num);
                // 生成订单
                HyPayRecord payRecord = new HyPayRecord();
                payRecord.setCreatedate(new Date());
               // payRecord.setGid(0);
                payRecord.setTotal(num);
                payRecord.setMoney(num);
                payRecord.setNum(0);
                payRecord.setType(PayType.backdoor_reduce.getCode());
               // payRecord.setCid(0);
                //payRecord.setChannel(0);
                payRecord.setPercentCoin(0);
                payRecord.setPercent(0.0f);
                payRecord.setYid(FrogConstant.admin_uid);
                // 扣费者id
                payRecord.setUid(uid);
                //payRecord.setVid(0);
                payRecordService.save(payRecord);

                // 生成交易明细
                ChargePayRecordEntity chargePayRecord = new ChargePayRecordEntity();
                chargePayRecord.setUid(uid);
                Calendar now = Calendar.getInstance();
                int year = now.get(Calendar.YEAR);
                int month = now.get(Calendar.MONTH) + 1;
                String monthN;
                if(month < 10){
                    monthN = "0" + month + "";
                }else{
                    monthN = month + "";
                }
                int day = now.get(Calendar.DAY_OF_MONTH);
                chargePayRecord.setOutTradeNo(year + "" + monthN  + day  + "" +  System.currentTimeMillis() + "");
                chargePayRecord.setTotalAmount(0);
                chargePayRecord.setCoin(-num);
                chargePayRecord.setType(0);
               // chargePayRecord.setPresentCoin(0);
                chargePayRecord.setCreateDate(new Date());
                chargePayRecord.setReceiptAmount(new BigDecimal(0));
                chargePayRecord.setBuyerPayAmount(new BigDecimal(0));
                chargePayRecord.setUpdateDate(new Date());
                chargePayRecord.setChargePresentCoin(0);
                chargePayRecord.setStatus(Constants.PayStatus.SUCCESS);
                chargePayRecord.setTerminal(Terminal.DisplayChannel.system);
                chargePayRecord.setChannel(Constants.PayChannel.SYSTEM_REDUCE);
                if(remark != null){
                    chargePayRecord.setRemark(remark);
                }
                chargePayRecordService.save(chargePayRecord);
                return R.ok("扣款成功");
            }
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }


}
